<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="零售编码" prop="marketId">
        <el-input
          v-model="queryParams.marketId"
          placeholder="请输入零售编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配料" prop="burden">
        <el-input
          v-model="queryParams.burden"
          placeholder="请输入配料"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存储方式" prop="storageMethod">
       <el-select  v-model="queryParams.storageMethod"  placeholder="请选择存储方式" clearable>
          <el-option
            v-for="item in options"
            :label="item.dictLabel"
            :value="item.dictCode"
            :key="item.dictCode">
          </el-option>
       </el-select>
      </el-form-item>
      <el-form-item label="保质期" prop="expirationDate">
        <el-input
          v-model="queryParams.expirationDate"
          placeholder="请输入保质期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入生产厂家"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品id" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="零售编码" align="center" prop="marketId" />
      <el-table-column label="配料" align="center" prop="burden" />
      <el-table-column label="净含量" align="center" prop="netContent" />
      <el-table-column label="有效期" align="center" prop="expirationDate" />
      <el-table-column label="货物数量" align="center" prop="num" />
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="存储方式" align="center" prop="storageMethodName" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" />
      <el-table-column label="生产日期" align="center" prop="productDate" width="180" />
      <el-table-column label="产地" align="center" prop="address" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.cname}}/{{scope.row.sname}}/{{scope.row.xname}}</span>
        </template>
      </el-table-column>
      <el-table-column label="溯源码" align="center" prop="sourceCode" >
      <template v-slot="scope">
        <el-image :src="scope.row.sourceCode" :preview-src-list="[scope.row.sourceCode]" style="width: 100px; height: 100px;"></el-image>
      </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="零售编码" prop="marketId">
          <el-input v-model="form.marketId" placeholder="请输入零售编码" maxlength="20" style="width: calc(100% - 100px); display: inline-block; margin-right: 3px;" />
          <el-switch
            v-model="value"
            active-color="#13ce66"
            inactive-color="#D5D8DC"
            style="display: inline-block;"
            @change="handleSwitchChange">
          </el-switch>
          <span>自动生成</span>
        </el-form-item>
        <el-form-item label="配料" prop="burden" disabled="">
          <el-input v-model="form.burden" placeholder="请输入配料"  />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="货物数量" v-model="form.num" prop="num">
          <el-input-number v-model="form.num" @change="handleChange"   label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="存储方式" prop="storageMethod">
          <el-select v-model="form.storageMethod" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="净含量" prop="netContent">
          <el-input v-model="form.netContent" placeholder="请输入净含量" />
        </el-form-item>
        <el-form-item label="保质期" prop="expirationDate">
          <el-input v-model="form.expirationDate" placeholder="请输入保质期" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="地址" prop="parentId">
          <el-cascader
            v-model="adresslist"
            :options="option"
            :props="{  expandTrigger: 'hover' ,label:'cityName', value:'cityId'}"
            @change="handleChang">
          </el-cascader>
        </el-form-item>
        <el-form-item label="溯源码" prop="sourceCode">
          <el-upload
            class="avatar-uploader"
            :action=upload.url
            :headers = upload.headers
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { SanjiList,listProduct, getProduct, delProduct, addProduct, updateProduct,ListType } from "@/api/source/product/product";
import {getToken} from "@/utils/auth";

export default {
  name: "Product",
  data() {
    return {
      adresslist:[],
      option:[],
      imageUrl:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      options: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        productName: null,
        marketId: null,
        burden: null,
        phone: null,
        storageMethod: null,
        netContent: null,
        expirationDate: null,
        manufacturer: null,
        isFault: null
      },

      upload: {
        headers: { Authorization: "Bearer " + getToken()},
        url: process.env.VUE_APP_BASE_API + "/source/crop/file/upload"
      },
      value:false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        marketId: [
           { required: true, message: "零售编号不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话号码不能为空", trigger: "blur" }
        ],
        storageMethod: [
          { required: true, message: "储存方式不能为空", trigger: "blur" }
        ],
        netContent: [
          { required: true, message: "净含量不能为空", trigger: "blur" }
        ],
        expirationDate: [
          { required: true, message: "保质期不能为空", trigger: "blur" }
        ],
        manufacturer: [
          { required: true, message: "生产厂家不能为空", trigger: "blur" }
        ],
        num: [
          { required: true, message: "货物数量不能为空", trigger: "blur" }
        ],
        productDate:[
          { required: true, message: "生产日期不能为空", trigger: "blur" }
        ],
        remark:[
          { required: true, message: "备注不能为空", trigger: "blur" }
        ],


      },

    };
  },
  created() {
    this.getList();
    this.typeList();
    this.sanjiList();

  },
  methods: {

    sanjiList(){
      SanjiList().then(response=>{
        this.option=response;
      })
    },
    handleChang(value) {
      this.adresslist=value;
      this.form.provinceId=this.adresslist[0];
      this.form.cityId=this.adresslist[1];
      this.form.countyId=this.adresslist[2];
      console.log(value);
    },
    //图片
    handleAvatarSuccess(res,file){
      console.log(file.response.msg);
      this.imageUrl = file.response.msg;
      this.form.sourceCode=file.response.msg;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSwitchChange(newValue) {
      // newValue 是开关的新状态，true 表示启用，false 表示禁用
      if (newValue) {
        // 如果开关启用时调用的方法
        this.form.marketId='C'+Math.floor(Math.random() * 100000)
      }
    },


    /** 查询产品信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },


    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        marketId: null,
        burden: null,
        phone: null,
        storageMethod: null,
        netContent: null,
        expirationDate: null,
        manufacturer: null,
        isFault: null
      };
      this.resetForm("form");
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },


    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },


    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.burden='水、白砂糖、果葡萄糖浆、食用盐、食用香精、防腐剂';
      this.open = true;
      this.title = "添加产品信息";
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data;
        this.imageUrl=response.data.sourceCode;
        console.log(this.imageUrl);
        this.adresslist=[];
        this.adresslist.push(this.form.provinceId);
        this.adresslist.push(this.form.cityId);
        this.adresslist.push(this.form.countyId);
        this.open = true;
        this.title = "修改产品信息";

      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /**存储类型 */
    typeList(){
      ListType().then(res=>{
        this.options=res.data;
        console.log(res);
      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除产品信息编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
